import os

from openai import OpenAI

os.environ['DASHSCOPE_API_KEY'] = 'sk-dd4911ae1b83470cbb87cb75ccf60794'
client = OpenAI(
    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)


# 结合上下文理解图片
def image_analysis(documents):
    prompt = """这是一段客户聊天记录，图片和聊天记录都是客户提出的问题，需要根据图片和聊天记录总结一下内容。字数不超过100字。
     ## 聊天记录 
     
    """
    image_list = []
    for document in documents:
        if document['type'] == 'image':
            image_list.append(
                {
                    "type": "image_url",
                    "image_url": {
                        "url": document['image_url']
                    }
                }
            )
        elif document['type'] == 'text':
            prompt += document['content'] + '\n'

    image_list.append(
        {"type": "text", "text": prompt}
    )
    messages = [
        {
            "role": "user",
            "content": image_list,
        }
    ]

    completion = client.chat.completions.create(
        model="qwen-vl-plus",
        messages=messages,
    )
    # print(completion.choices[0].message.content)
    return completion.choices[0].message.content